package org.budo.support.java.regex.pattern.factory;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;

import org.budo.support.lang.util.StringUtil;

import lombok.extern.slf4j.Slf4j;

/**
 * @author lmw
 */
@Slf4j
public class RegexPatternFactory {
    private static final RegexPatternFactory _PATTERN_FACTORY_INSTANCE = new RegexPatternFactory();

    private Map<String, Pattern> _PATTERN_CACHE = new HashMap<String, Pattern>();

    public static RegexPatternFactory getInstance() {
        return _PATTERN_FACTORY_INSTANCE;
    }

    /**
     * @param regex
     * 
     * @return 如果传入字符串为空,则返回空对象
     */
    public Pattern getPattern(String regex, int flags) {
        if (StringUtil.isEmpty(regex)) {
            log.error("getPattern error, regex is empty, regex=" + regex + ", flags=" + flags);
            return null;
        }

        String cacheKey = flags + "#" + regex;
        Pattern patternResult = _PATTERN_CACHE.get(cacheKey);
        if (null == patternResult) {
            synchronized (RegexPatternFactory.this) {
                patternResult = _PATTERN_CACHE.get(cacheKey);
                if (null == patternResult) {
                    Pattern patternNew = Pattern.compile(regex, flags);
                    _PATTERN_CACHE.put(cacheKey, patternNew);
                    patternResult = patternNew;
                }
            }
        }

        return patternResult;
    }

    /**
     * @see java.util.regex.Pattern#compile(String)
     */
    public Pattern getPattern(String regex) {
        return this.getPattern(regex, 0);
    }
}